import React, {useEffect} from 'react';
interface Result {
  page: Page;
  loading: boolean;
  loadComplete: boolean;
  resetPage: () => void;
  nextPage: () => void;
}

interface Page {
  pageNo: number;
  pageSize: number;
  totalPage: number;
  list: any[];
}

interface Option {
  showLoading?: boolean;
}

export default function usePageMixin(
  fn: Function,
  params: any = {},
  option: Option = {showLoading: true},
): Result {
  const [page, onChangePage] = React.useState({
    pageNo: 1,
    pageSize: 10,
    totalPage: -1,
    list: [],
  });

  const [loading, onChangeLoading] = React.useState(false);

  const [loadComplete, onChangeLoadComplete] = React.useState(false);
  let requestApi: Function = fn;
  let requestParam: any = params;
  let optionParam: Option = option;

  /**
   * 重置分页
   *
   */
  function resetPage(): void {
    onChangePage({
      ...page,
      pageNo: 1,
    });
    if (requestParam.pageSize) page.pageSize = requestParam.pageSize;
    page.totalPage = -1;
    onChangeLoading(false);
    onChangeLoadComplete(false);
  }

  /**
   * 数据赋值
   */
  function setPageData(rs: any): void {
    onChangeLoading(false);
    onChangeLoadComplete(rs.pageNo >= rs.totalPage ? true : false);
    onChangePage({
      ...page,
      pageNo: rs.pageNo,
      pageSize: rs.pageSize,
      totalPage: rs.totalPage,
      list: page.pageNo === 1 ? rs.list : page.list.concat(rs.list),
    });
  }

  /**
   * 将传入的分页数据和查询条件数据混合为一个对象，并查询数据
   */
  function queryByPageAndParam(): void {
    console.log('请求', page);
    const {pageNo, pageSize, totalPage} = page;
    if (totalPage != -1 && pageNo > totalPage) {
      return;
    }

    if (pageNo === 1 && optionParam.showLoading) {
      // uni.showLoading({
      // 	title: '加载中'
      // })
    }
    if (loading) {
      return;
    }

    const args: any = {pageNo, pageSize};
    for (let key in requestParam) {
      if (requestParam[key] || requestParam[key] === 0) {
        args[key] = requestParam[key];
      }
    }
    onChangeLoading(true);
    requestApi(args).then(
      (rs: any) => {
        // uni.hideLoading()
        onChangeLoading(false);
        setPageData(rs);
      },
      (err: any) => {
        // uni.hideLoading()
        onChangeLoading(false);
      },
    );
  }

  /**
   * 加载更多
   */
  function nextPage(): void {
    const {totalPage, pageNo} = page;
    if (totalPage !== -1 && pageNo < totalPage) {
      page.pageNo += 1;
      queryByPageAndParam();
    }
  }

  useEffect(() => {
    resetPage();
    queryByPageAndParam();
  }, []);

  return {
    page,
    loading,
    loadComplete,
    resetPage,
    nextPage,
  };
}
